package learn_concurrent._2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T3 {
	final static Logger logger = LoggerFactory.getLogger(T3.class);
	
	public static void main(String[] args) throws InterruptedException {
		for(int i = 0; i < 500000; i++) {
			test1();
		}
		
	}

	private static void test1() throws InterruptedException {
		Room room = new Room();
		
		Thread t1 = new Thread(() -> {
			for(int i = 0; i < 5000; i++) {
				room.increment();
			}
		});
		
		Thread t2 = new Thread(() -> {
			for(int i = 0; i < 5000; i++) {
				room.decrement();
			}
		});
		
		t1.start();
		t2.start();
		
		t1.join();
		t2.join();
		
		if(room.getCount() != 0) {
			throw new IllegalArgumentException(room.getCount() + "");
		}
	}
}

class Room {
	private int count = 0;
	
	public void increment() {
		synchronized(this) {
			count++;
		}
	}
	
	public void decrement() {
		synchronized(this) {
			count--;
		}
	}
	
	public int getCount() {
		return count;  // ??? need synchronized ???
	}
}
















